from .base import Base, account_moneys
from sqlalchemy.schema import Column, ForeignKey, UniqueConstraint
from sqlalchemy.types import Integer, UnicodeText
from sqlalchemy.databases import mysql
from sqlalchemy.orm import relation, backref
from database.User import User
from database.Money import Money

__all__ = ["Account"]

class Account(Base):
    __tablename__ = "accounts"
    
    id = Column(Integer, primary_key=True)
    name = Column(mysql.MSString(255), nullable=False)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    
    user = relation(User, backref=backref('accounts', order_by=id))
    initialAmounts = relation(Money, secondary=account_moneys, cascade="all, delete, delete-orphan", lazy=False)

    __table_args__ = (UniqueConstraint("name", "user_id"), {}) 
    
    def __init__(self, name):
        self.name = name

    def getData(self):
        class ArrayOfMoney:
            _money = map(Money.getData, self.initialAmounts)
        class Account:
            _id = self.id
            _name = self.name
            _initialAmounts = ArrayOfMoney 
        return Account
        
    def __repr__(self):
        return "<Account('%s')>" % self.name